package com.goodfox.web.generic.authority.service.impl;

import java.util.Collection;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.stereotype.Service;

import com.goodfox.web.generic.account.entity.Account;
import com.goodfox.web.generic.attribute.controller.AttributeController;
import com.goodfox.web.generic.authority.filter.SecurityMetadataSourceImpl;
import com.goodfox.web.generic.authority.service.PowerService;
import com.goodfox.web.generic.role.entity.Role;

/**
 * 权限Service实现类
 * @author qin gt
 *
 */
@Service(value="powerService")
public class PowerServiceImpl implements PowerService {

	/** log4j日志器 */
	private Logger logger = Logger.getLogger(PowerServiceImpl.class);

	/**
	 * 判断使用登录账号是否有访问该url的权限
	 * @param account 当前登录账号
	 * @param useUrl 访问的Url
	 * @return
	 */
	public boolean havePower(Account account,String useUrl){
		boolean isAuthority=false;
		if(account!=null){
			try{
				Map<String, Collection<ConfigAttribute>> powerMap=SecurityMetadataSourceImpl.resourcesMap;
				Collection<ConfigAttribute> configList=powerMap.get(useUrl);
				if(configList!=null){
					for(ConfigAttribute config:configList){
						if(account.getRole().getRolePower().equals(config.getAttribute())){
							isAuthority=true;
							break;
						}
					}
				}
			}catch(Exception ex){
				logger.error("判断权限时发生异常",ex);
			}
		}
		return isAuthority;
	}
	
	public Account havePower(HttpServletRequest request){
		boolean isAuthority=false;
		Account loginAccount=null;
		try{
			loginAccount=(Account)request.getSession().getAttribute("loginAccount");
			String useUrl=request.getRequestURI().toString().substring(1);
			useUrl=useUrl.substring(useUrl.indexOf("/"));
			if(useUrl.indexOf(".shtml;")>0){
				useUrl=useUrl.substring(0,useUrl.indexOf(".shtml;")+6);
			}
			Map<String, Collection<ConfigAttribute>> powerMap=SecurityMetadataSourceImpl.resourcesMap;
			Collection<ConfigAttribute> configList=powerMap.get(useUrl);
			if(configList!=null){
				for(ConfigAttribute config:configList){
					if(loginAccount.getRole().getRolePower().equals(config.getAttribute())){
						isAuthority=true;
						break;
					}
				}
			}
		}catch(Exception ex){
			logger.error("判断权限时发生异常",ex);
		}
		if(!isAuthority){
			loginAccount=null;
		}
		return loginAccount;
	}
}
